package com.wusuowei.common.listener;

import com.wusuowei.common.model.po.ComOperLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author wangzhenjun
 * @date 2022/10/25 15:22
 */
@Slf4j
@Component
public class MyEventListener {

    @Autowired
    JdbcTemplate jdbcTemplate;
    // 开启线程池异步
    @Async("asyncExecutor")
    // 开启监听
    @EventListener(ComOperLog.class)
    public void saveSysLog(ComOperLog event) {
        String sql = "INSERT INTO `sys_oper_log` VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, null);
                preparedStatement.setString(2, event.getTitle());
                preparedStatement.setInt(3, event.getBusinessType());
                preparedStatement.setString(4, event.getMethod());
                preparedStatement.setString(5, event.getRequestMethod());
                preparedStatement.setInt(6, 0);
                preparedStatement.setString(7, event.getOperName());
                preparedStatement.setString(8, event.getDeptName());
                preparedStatement.setString(9, event.getOperUrl());
                preparedStatement.setString(10, event.getOperIp());
                preparedStatement.setString(11, event.getOperLocation());
                preparedStatement.setString(12, event.getOperParam());
                preparedStatement.setString(13, event.getJsonResult());
                preparedStatement.setInt(14, event.getStatus());
                preparedStatement.setString(15, event.getErrorMsg());
                preparedStatement.setString(16, event.getOperTime().toString());
                preparedStatement.setLong(17, event.getCostTime());
                return preparedStatement;
            }
        });
        log.info("=====即将异步保存到数据库======");
    }

}
